import axios from "axios";
import qs from "qs";

// 默认超时时间60s
axios.defaults.timeout = 60000;

// Request 拦截器: 添加 token
axios.interceptors.request.use(
    config => {
        if (app.util.sessionStorage("token")) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            if (app.config.setting.platform === 'mobile') {
                app.util.localStorage('tokenTime', new Date().getTime());//更新时间
                config.headers.Authorization = app.util.sessionStorage('token');
            } else {
                config.headers.Authorization = app.util.sessionStorage("token");
            }
        }

        return config;
    },
    err => {
        return Promise.reject(err);
    });
// Response 拦截器： 处理异常
axios.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        if (error.response) {
            if (error.response.status === 401) {
                if (app.config.setting.platform === 'mobile') {
                    window.plus.nativeUI.closeWaiting();
                } else {
                    this.$indicator.close();
                }
                vm.$toast('抱歉：非正常登录或者当前回话超时，请重新登录');
                setTimeout(() => {
                    if (app.config.setting.platform === 'wechat') {
                        wx.closeWindow();
                    }
                    if (!app.util.sessionStorage('token')) {
                        // vm.$toast('您还没有登录呢，请重新登录');
                        // setTimeout(() => {
                        vm.$router.push({path: '/login'});
                        // }, 2000)
                    }
                }, 2000);
            } else {
                vm.$toast('抱歉：系统发生不可预知错误[' + error.response.status + ']');
            }
            // 请求已发出，但服务器响应的状态码不在 2xx 范围内
            processError(error);
            console.log(error.response.data);
        } else {
            vm.$toast('授权验证失败，服务器拒绝您的请求，正在跳转登录，请稍后...');
            console.log('Error', error.message);
            setTimeout(() => {
                if (app.config.setting.platform === 'wechat') {
                    wx.closeWindow();
                } else {
                    vm.$router.push({path: '/login'});
                }
            }, 2000);
        }
        return Promise.reject(error);
    });

export default {
    all(gets, cb) {
        // 请求函数数组
        let functions = [];
        gets.forEach(function (get) {
            if (get.url) {
                functions.push(axios.get(processUrl(get.url), {
                    params: get.params
                }));
            }
        });

        // 并发请求
        let results = [];
        axios.all(functions).then(axios.spread(function (..._results) {
            _results.forEach((_result) => {
                results.push(_result.data.data);
            });
            cb(null, results);
        })).catch(function (error) {
            processError(error);
        });
    },
    get(url, params, cb_suc, cb_err) {
        axios.get(processUrl(url), {
            params: params
        })
            .then(function (resp) {
                if (resp.data.s !== undefined) {
                    if (resp.data.s === 0) {
                        if (typeof cb_suc === "function") cb_suc(resp.data);
                    } else {
                        vm.$toast({duration: '2000', message: resp.data.msg});
                        app.logger.error('get fail', resp.data);
                        if (typeof cb_err === "function") cb_err(resp);
                    }
                } else {
                    vm.$toast({duration: '2000', message: resp.data.message});
                    app.logger.error('get fail', resp);
                    if (typeof cb_err === "function") cb_err(resp);
                }
            })
    },
    put(url, data, cb_suc, cb_err) {
        vm.$indicator.open();
        axios.put(processUrl(url), qs.stringify(data))
            .then(function (resp) {
                vm.$indicator.close();
                if (resp.data.s !== undefined) {
                    if (resp.data.s === 0) {
                        vm.$toast({
                            duration: '2000',
                            message: resp.data.msg === 'ok' ? '成功' : resp.data.msg
                        });
                        if (typeof cb_suc === "function") cb_suc(resp.data);
                    } else {
                        vm.$toast({duration: '2000', message: resp.data.msg});
                        if (app.config.setting.platform === 'mobile') {
                            window.plus.nativeUI.closeWaiting();
                        }
                        app.logger.error('put fail', resp.data);
                        if (typeof cb_err === "function") cb_err(resp);
                    }
                } else {
                    vm.$toast({duration: '2000', message: resp.data.message});
                    if (app.config.setting.platform === 'mobile') {
                        window.plus.nativeUI.closeWaiting();
                    }
                    app.logger.error('put fail', resp);
                    if (typeof cb_err === "function") cb_err(resp);
                }
            })
    },
    post(url, data, cb_suc, cb_err) {
        vm.$indicator.open();
        axios.post(processUrl(url), qs.stringify(data))
            .then(function (resp) {
                vm.$indicator.close();
                if (resp.data.s !== undefined) {
                    if (resp.data.s === 0) {
                        vm.$toast({
                            duration: '2000',
                            message: resp.data.msg === 'ok' ? '成功' : resp.data.msg
                        });
                        if (typeof cb_suc === "function") cb_suc(resp.data);
                    } else {
                        vm.$toast({duration: '2000', message: resp.data.msg});
                        if (app.config.setting.platform === 'mobile') {
                            window.plus.nativeUI.closeWaiting();
                        }
                        app.logger.error('post fail', resp.data);
                        if (typeof cb_err === "function") cb_err(resp);
                    }
                } else {
                    vm.$toast({duration: '2000', message: resp.data.message});
                    if (app.config.setting.platform === 'mobile') {
                        window.plus.nativeUI.closeWaiting();
                    }
                    app.logger.error('post fail', resp);
                    if (typeof cb_err === "function") cb_err(resp);
                }
            })
    },
    delete(url, params, cb_suc, cb_err) {
        vm.$indicator.open();
        axios.delete(processUrl(url), {
            params: params
        })
            .then(function (resp) {
                vm.$indicator.close();
                if (resp.data.s !== undefined) {
                    if (resp.data.s === 0) {
                        vm.$toast({
                            duration: '2000',
                            message: resp.data.msg === 'ok' ? '成功' : resp.data.msg
                        });
                        if (typeof cb_suc === "function") cb_suc(resp.data);
                    } else {
                        vm.$toast({duration: '2000', message: resp.data.msg});
                        if (typeof cb_err === "function") cb_err(resp);
                    }
                } else {
                    vm.$toast({duration: '2000', message: resp.data.message});
                    if (typeof cb_err === "function") cb_err(resp);
                }
            })
    },
    /**
     * 自定义：仅支持 put、post
     * @param url
     * @param method
     * @param data
     * @param cb_suc
     * @param cb_err
     */
    custom(url, method, data, cb_suc, cb_err) {
        axios.request({
            url: processUrl(url),
            method: method,
            data: qs.stringify(data)
        })
            .then(function (resp) {
                if (resp.data) {
                    if (typeof cb_suc === "function") cb_suc(resp.data);
                } else {
                    app.logger.error('ajax custom fail', resp);
                    if (typeof cb_err === "function") cb_err(resp);
                }
            })
            .catch(function (err) {
                if (typeof cb_err === "function") cb_err(err);
            });
    }
}

// 添加服务器端URL
function processUrl(url) {
    if (url.indexOf('http://') > -1) {  // 跨网段访问
        return url;
    }
    return app.config.setting.server + url;
}

// 请求error处理
function processError(error) {
    let detail;
    if (error.response) {   // 请求已发出，但服务器响应的状态码不在 2xx 范围内
        detail = JSON.stringify(error.response.data);
        vm.$toast({duration: '2000', message: '异常，响应状态码：' + error.response.status});
    } else {
        detail = JSON.stringify(error);
        vm.$toast({duration: '2000', message: '异常：' + error.message});
    }
    setTimeout(() => {
        sessionStorage.setItem('error', '系统拒绝您的请求或网络出现故障');
        sessionStorage.setItem('detail', detail);
        // vm.$router.push({path: '/error'});
    }, 1000);
}
